const app = getApp()
Page({
  data: {
    remote_src: app.globalData.remote_src,
    showAge: true,
    showProfession: true,
    showCity: true,
    showInterests: true,
    showEditModal: false,
    showEditModal: false,
    editModalTitle: '',
    editModalPlaceholder: '',
    editModalValue: '',
    currentEditField: '',
    userInfo: app.globalData.userInfo,
    showInterestModal: false,
    interestList: [
      { id: 1, name: '运动', selected: false },
      { id: 2, name: '摄影', selected: false },
      { id: 3, name: '约饭', selected: false },
      { id: 4, name: '电影', selected: false },
      { id: 5, name: '旅游', selected: false },
      { id: 6, name: '购物', selected: false },
      { id: 7, name: '游戏', selected: false },
      { id: 8, name: '阅读', selected: false },
      { id: 9, name: '音乐', selected: false },
      { id: 10, name: '美食', selected: false },
      { id: 11, name: '健身', selected: false },
      { id: 12, name: '瑜伽', selected: false }
    ]
  },

  onLoad() {
    // this.getPrivacySettings()
    // this.data.userInfo = app.globalData.userInfo;
    console.log(app.globalData.userInfo)
    if (app.globalData.userInfo) {
      // 解析兴趣字符串为JSON对象
      let userInfo = JSON.parse(JSON.stringify(app.globalData.userInfo));
    
      if (userInfo.interests) {
        try {
          userInfo.interests = JSON.parse(userInfo.interests);
           // 更新兴趣列表选中状态
           const interestList = this.data.interestList.map(item => {
            item.selected = userInfo.interests.some(interest => interest.id === item.id);
            return item;
          });
          this.setData({
            interestList: interestList
          });
        } catch (e) {
          userInfo.interests = [];
        }
      }
      if(userInfo.mask_info){
        userInfo.mask_info = typeof userInfo.mask_info === 'object' ? 
        userInfo.mask_info : JSON.parse(userInfo.mask_info);
        console.log(userInfo.mask_info)
          this.setData({
            'showAge': userInfo.mask_info.age,
           'showProfession': userInfo.mask_info.profession,
           'showCity': userInfo.mask_info.city
          })
      }
      console.log(userInfo)
      this.setData({
        userInfo: userInfo
      });
    }
  },

  getPrivacySettings() {
    const app = getApp()
    wx.request({
      url: app.globalData.offlineService + '/api/user/privacy',
      method: 'GET',
      success: (res) => {
        if (res.data.status === 'success') {
          this.setData({
            showAge: res.data.settings.showAge,
            showProfession: res.data.settings.showProfession,
            showCity: res.data.settings.showCity,
            showInterests: res.data.settings.showInterests
          })
        }
      }
    })
  },

  toggleAge(e) {
    console.log(this.data.userInfo)
    this.data.userInfo.mask_info.age = e.detail.value;
    this.updateMaskInfo('mask_info',JSON.stringify(this.data.userInfo.mask_info))
    app.globalData.userInfo.mask_info = JSON.stringify(this.data.userInfo.mask_info);
  },

  toggleProfession(e) {
    this.data.userInfo.mask_info.profession = e.detail.value;
    this.updateMaskInfo('mask_info',JSON.stringify(this.data.userInfo.mask_info));
    app.globalData.userInfo.mask_info = JSON.stringify(this.data.userInfo.mask_info);
  },

  toggleCity(e) {
    this.data.userInfo.mask_info.city = e.detail.value;
    this.updateMaskInfo('mask_info',JSON.stringify(this.data.userInfo.mask_info));
    app.globalData.userInfo.mask_info = JSON.stringify(this.data.userInfo.mask_info);
  },
  updateMaskInfo(field, value) {  
    if (!value) {
      wx.showToast({
        title: '内容不能为空',
        icon: 'error'
      }) 
      return;
    }
    wx.request({
      url: getApp().globalData.onlineService + '/api/girls/girls',
      method: 'PUT',
      header: {
        'Authorization': 'Bearer '+ this.data.userInfo.token,
        'content-type': 'application/json'
      },
      data: {
        [field]: value,
      },
      success: (res) => {
        console.log(res)
        if (res.data.code === 200) {
          wx.showToast({
            title: '更新成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: '更新失败',
            icon: 'error'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误',
          icon: 'error'
        });
      } 
    })
  },

  toggleInterest(e) {
    const id = e.currentTarget.dataset.id;
    const interestList = this.data.interestList;
    const index = interestList.findIndex(item => item.id === id);
    
    // 限制最多选择5个兴趣
    const selectedCount = interestList.filter(item => item.selected).length;
    if (!interestList[index].selected && selectedCount >= 5) {
      wx.showToast({
        title: '最多选择5个兴趣',
        icon: 'none'
      });
      return;
    }
    // 切换选中状态
    interestList[index].selected = !interestList[index].selected;
    this.setData({
      interestList: interestList
    });
  },
  saveInterests() {
    // 获取选中的兴趣
    const selectedInterests = this.data.interestList
      .filter(item => item.selected)
      .map(item => ({
        id: item.id,
        name: item.name
      }));

    // 转换为JSON字符串
    const interestsJson = JSON.stringify(selectedInterests);
    console.log(interestsJson)
    // 调用更新接口
    this.updateSetting('interests', interestsJson);
    
    // 关闭弹窗
    this.setData({
      showInterestModal: false
    });
  },
  updateSetting(field, value) {
    if (!value) {
      wx.showToast({
        title: '内容不能为空',
        icon: 'error'
      }) 
      return;
    }
    // 如果是年龄字段，转换为整数
    if (field === 'age') {
      value = parseInt(value);
      if (isNaN(value) || value < 0 || value > 120) {
        wx.showToast({
          title: '请输入有效年龄',
          icon: 'error'
        });
        return;
      }
    }
    console.log(this.data.userInfo)
    wx.request({
      url: getApp().globalData.onlineService + '/api/girls/girls',
      method: 'PUT',
      header: {
        'Authorization': 'Bearer '+ this.data.userInfo.token,
        'content-type': 'application/json'
      },
      data: {
        [field]: value,
      },
      success: (res) => {
        console.log(res)
        if (res.data.code === 200) {
          // 更新本地数据
          this.setData({
            [`userInfo.${field}`]: value,
            showEditModal: false,
            editModalValue: ''
          });
          getApp().globalData.userInfo = this.data.userInfo;
          wx.showToast({
            title: '更新成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: '更新失败',
            icon: 'error'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误',
          icon: 'error'
        });
      } 
    })
  },
  goToEditName() {
    this.setData({
      showEditModal: true,
      editModalTitle: '昵称',
      editModalPlaceholder: '请输入昵称',
      editModalValue: this.data.userInfo.name || '',
      currentEditField: 'name'
    })
  },
    // 打开编辑弹窗
    goToEditAge() {
      this.setData({
        showEditModal: true,
        editModalTitle: '年龄',
        editModalPlaceholder: '请输入年龄',
        editModalValue: this.data.userInfo.age || '',
        currentEditField: 'age'
      })
    },
    goToEditProfession() {
      this.setData({
        showEditModal: true,
        editModalTitle: '职业',
        editModalPlaceholder: '请输入职业',
        editModalValue: this.data.userInfo.profession || '',
        currentEditField: 'profession'
      })
    },
  
    goToEditCity() {
      this.setData({
        showEditModal: true,
        editModalTitle: '城市',
        editModalPlaceholder: '请输入城市',
        editModalValue: this.data.userInfo.city || '',
        currentEditField: 'city'
      })
    },
    // 打开兴趣选择弹窗
    showInterestSelect() {
      this.setData({
        showInterestModal: true
      })
    },
      // 关闭兴趣选择弹窗
  closeInterestModal() {
    this.setData({
      showInterestModal: false
    });
    // this.saveInterests();
  },
    // 处理输入框值变化
  onModalInput(e) {
      this.setData({
        editModalValue: e.detail.value
      })
    },
    // 取消编辑
  cancelEdit() {
    this.setData({
      showEditModal: false,
      editModalValue: ''
    })
  },
  confirmEdit() {
    let field = this.data.currentEditField;
    let value = this.data.editModalValue;
    this.updateSetting(field, value)
  },
    // 打开头像编辑弹窗
    changeAvatar() {
      this.setData({
        showAvatarModal: true
      })
    },
  
    // 关闭头像编辑弹窗
    closeAvatarModal() {
      this.setData({
        showAvatarModal: false
      })
    },
  
    // 从相册选择
    chooseFromAlbum() {
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album'],
        success: (res) => {
          this.uploadAvatar(res.tempFilePaths[0])
        }
      })
    },
  
    // 拍照
    takePhoto() {
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['camera'],
        success: (res) => {
          this.uploadAvatar(res.tempFilePaths[0])
        }
      })
    },
  
    // 上传头像
    uploadAvatar(filePath) {
      const that = this;
      console.log(getApp().globalData.onlineService + '/api/infra/file')
      wx.uploadFile({
        url: getApp().globalData.onlineService + '/api/infra/file',
        filePath: filePath,
        name: 'file',
        success: (res) => {
          const data = JSON.parse(res.data)
          console.log(data)
          const photo_url = getApp().globalData.onlineService + '/api/infra/file?filename=' + data.filename
          if (data.code === 200) {
            this.setData({
              // 'userInfo.photo_url': photo_url,
              showAvatarModal: false
            })
            that.updateSetting('photo_url', photo_url)
            wx.showToast({
              title: '更新成功',
              icon: 'success'
            })
          }else{
            this.setData({
              showAvatarModal: false
            })
            wx.showToast({
              title: '更新失败',
              icon: 'error'
            });
          }
        },
        fail(err) {
          wx.showToast({
            title: '上传失败',
            icon: 'error'
          });
        },
        complete() {
          // 上传完成后的回调（可选）
        }
      })
    }
})